package com.example.rbacmanage.service.app.impl;

import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.app.Photo;
import com.example.rbacmanage.entity.app.Uv;
import com.example.rbacmanage.mapper.app.UvMapper;
import com.example.rbacmanage.service.app.UvService;
import com.example.rbacmanage.util.AddressUtils;
import com.example.rbacmanage.util.DateUtils;
import com.example.rbacmanage.util.IpUtils;
import com.example.rbacmanage.util.ServletUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UvServiceImpl implements UvService {
    @Autowired
    private UvMapper uvMapper;
    @Override
    public void save(Uv uv) {
        UserAgent userAgent = eu.bitwalker.useragentutils.UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        uv.setOs(os);
        uv.setBrowser(browser);
        uv.setSessionId(ServletUtils.getRequest().getSession().getId());
        uv.setIp(IpUtils.getIpAddr());
        uv.setIpLocation(AddressUtils.getRealAddressByIP(uv.getIp()));
        uv.setCreateTime(new Date());
        Uv uv1 = new Uv();
        uv1.setSessionId(uv.getSessionId());
        uv1.setIp(uv.getIp());
        uv1.setIpLocation(AddressUtils.getRealAddressByIP(uv1.getIp()));
        Map<String,Object> map = new HashMap<>();
        map.put("beginTime", DateUtils.getStartDate());
        map.put("endTime",DateUtils.getEndDate());
        uv1.setParams(map);
        Integer count = uvMapper.count(uv1);
        if(count != null && count > 0){
            return;
        }
        uvMapper.insert(uv);
    }

    @Override
    public void remove(Long[] ids) {
        for (Long id : ids) {
            uvMapper.del(id);
        }
    }

    @Override
    public void update(Uv uv) {
        uvMapper.update(uv);
    }

    @Override
    public List<Uv> getAll(Uv uv) {
        return uvMapper.list(uv);
    }


    @Override
    public PageInfo<Uv> getPage(Uv uv) {
        PageHelper.startPage(uv.getPage(),uv.getLimit());
        return new PageInfo<>(getAll(uv));
    }

    @Override
    public Uv getById(Long id) {
        return uvMapper.queryOneById(id);
    }

    @Override
    public Integer getCount(Uv uv) {
        return uvMapper.count(uv);
    }
}
